package com.zh.yqbj.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Component
public class EmailUtil {
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String EMAIL_SENDER;
    @Value("${spring.application.name}")
    private String EMAIL_SENDER_AUTH;
    @Value("${spring.servlet.multipart.location}")
    private String EMAIL_FILE_PATH_PREFIX;

    /**
     * 发送邮件
     *
     * @param to      接收方
     * @param title   邮件标题
     * @param content 邮件信息
     * @param files   文件数组
     * @throws MessagingException           错了
     * @throws UnsupportedEncodingException 不支持
     */
    public void sendEmailWithFile(String to, String title, String content, File[] files) throws MessagingException,
            UnsupportedEncodingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        // 创建 MimeMessageHelper，指定 boolean multipart 参数为 true
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人邮箱和名称
        helper.setFrom(EMAIL_SENDER, EMAIL_SENDER_AUTH);
        // 收件人邮箱
        helper.setTo(to);
        // 邮件标题
        helper.setSubject(title);
        // 邮件正文，第二个参数表示是否是HTML正文
        helper.setText(content, true);
        // 添加附件，指定附件名称、文件的 Inputstream 流 以及 Content-Type，附件只能是项目文件空间的文件
        for (File file : files) {
            helper.addAttachment(file.getName(),
                    () -> Files.newInputStream(Paths.get(EMAIL_FILE_PATH_PREFIX + file.getPath())),
                    "application/octet-stream");
        }
        // 发送
        javaMailSender.send(message);
    }

    /**
     * 发送邮件
     *
     * @param to      接收方
     * @param title   邮件标题
     * @param content 邮件信息
     * @throws MessagingException           错了
     * @throws UnsupportedEncodingException 不支持
     */
    public void sendEmail(String to, String title, String content) throws MessagingException,
            UnsupportedEncodingException {
        this.sendEmailWithFile(to, title, content, new File[]{});
    }

}
